package com.caine.multithread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: CaineZhu
 * @Description:
 * @Date: Created in 17:07 2020/12/10
 * @Modified By:
 */
public class ConditionDemo2 {
    static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        CountDownLatch latch = new CountDownLatch(1);
        char[] charabc = "abcdefgh".toCharArray();
        char[] char123 = "12345678".toCharArray();
        Condition condition1 = lock.newCondition();
        Condition condition2 = lock.newCondition();
        new Thread(() -> {
            try {
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            lock.lock();
            try {
                for (char c : charabc) {
                    System.out.print(c);
                    condition2.signal();
                    condition1.await();
                }
                condition2.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }, "t1").start();

        new Thread(() -> {
            latch.countDown();
            lock.lock();
            try {
                for (char c : char123) {
                    System.out.print(c);
                    condition1.signal();
                    condition2.await();
                }
                condition1.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }, "t2").start();
    }
}
